#!/bin/sh
para=$*

device=""
address=""
netmask=""
gw=""
isClear=""
ntp=""
isLoad=""
saveFile_dir="/userdata/"
saveFile_fileName="IMX6ULL_Info"


if [[ $1 = "clear" ]];then
    isClear="1"
fi

if [[ $1 = "load" ]];then
    isLoad="1"
fi

while getopts 'i:n:g:l:d:t:' OPT; do
    case $OPT in
        i) address="$OPTARG";;
        n) netmask="$OPTARG";;
        g) gw="$OPTARG";;
        l) device="$OPTARG";;
        d) aaa="$OPTARG";;
        t) ntp="$OPTARG";;
    esac
done

echo address:$address
echo netmask:$netmask
echo gw:$gw
echo device:$device
echo ntp:$ntp

run_ifconfig(){
    commandLine="ifconfig $device"
    if [[ -n $address ]];then
        commandLine="$commandLine $address"
    fi
    
    if [[ -n $netmask ]];then
        commandLine="$commandLine netmask $netmask"
    fi

    echo commandLine:$commandLine
    $commandLine
}

run_route(){
    if [[ -n $gw ]];then
        route add default gw $gw
    fi
}

run_ntp(){
    if [[ -n $ntp ]];then
        sntp -s $ntp
        hwclock -w
    fi
}


write_info_to_disk(){
    if [ ! -d $saveFile_dir ];then
        mkdir -p $saveFile_dir
    fi
    echo "#!/bin/sh" > $saveFile_dir$saveFile_fileName
    echo $address:$netmask:$gw >> $saveFile_dir$saveFile_fileName
    commandLine="ifconfig $device"
    if [[ -n $address ]];then
        commandLine="$commandLine $address"
    fi
    
    if [[ -n $netmask ]];then
        commandLine="$commandLine netmask $netmask "
    fi
    
    echo $commandLine >> $saveFile_dir$saveFile_fileName
    
    if [[ -n $gw ]];then
        commandLine="route add default gw $gw"
    fi
    echo $commandLine >> $saveFile_dir$saveFile_fileName
    
    commandLine="sleep 2";
    echo $commandLine >> $saveFile_dir$saveFile_fileName
     
    if [[ -n $ntp ]];then
        commandLine="sntp -s $ntp"
    fi
    echo $commandLine >> $saveFile_dir$saveFile_fileName

    commandLine=" hwclock -w"
    echo $commandLine >> $saveFile_dir$saveFile_fileName
   
}

main(){
    if [[ -n $isClear ]];then
        if [ -f $saveFile_dir$saveFile_fileName ];then
            rm $saveFile_dir$saveFile_fileName
        fi
    elif [[ -n $isLoad ]];then
        if [ -f $saveFile_dir$saveFile_fileName ];then
            #commandLine=`cat $saveFile_dir$saveFile_fileName`
            while read line
            do
                echo $line
                $line
            done < $saveFile_dir$saveFile_fileName

        fi
    else
        #1 install busybox
        #install_busybox
        #2 run ifconfig to temp modify
        run_ifconfig
        run_route
        run_ntp
        #3 modify config file to save ip info
        write_info_to_disk
    fi
}

main
